package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.sky.constant.RedisConstant.DISH_KEY;

/**
 * ClassName: DishServiceImpl
 * Package: com.sky.service.impl
 * Description:
 *
 * @Autehor 屈子岩
 * @Create 2024/9/5 11:57
 * @Version 1.0
 */
@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<Dish> page = dishMapper.PageQuery(dishPageQueryDTO);
        List<Dish> result = page.getResult();
        List<Object> list = result.stream().map(item -> {
            DishVO dish = new DishVO();
            Long categoryId = item.getCategoryId();
            BeanUtils.copyProperties(item, dish);
            dish.setCategoryName(categoryMapper.selectById(categoryId));
            return dish;
        }).collect(Collectors.toList());
        PageResult pageResult = new PageResult(page.getTotal(), list);
        return pageResult;
    }

    /**
     * 根据分类Id查询菜品
     *
     * @param categoryId
     * @return
     */
//    @Override
//    public List<Dish> list(Long categoryId) {
//        List<Dish> dish = dishMapper.selectByCategoryId(categoryId);
//        return dish;
//    }

    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public DishVO getById(Long id) {

        DishVO dishVO = dishMapper.getById(id);
        List<DishFlavor> dishFlavors = dishFlavorMapper.selcetByDishId(id);
        dishFlavors.stream().map(item -> {
            dishVO.setFlavors(dishFlavors);
            dishVO.setCategoryName(categoryMapper.selectById(dishVO.getCategoryId()));
            return dishVO;
        }).collect(Collectors.toList());
        return dishVO;
    }

    /**
     * 修改菜品状态
     *
     * @param status
     * @param id
     * @return
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = new Dish().builder()
                .status(status)
                .id(id)
                .build();
        dishMapper.update(dish);
    }

    /**
     * 批量删除菜品
     *
     * @param ids
     * @return
     */
    @Override
    public void deleteByIdWithFlavor(List<Long> ids) {
        log.info("Id为:{}", ids);
        for (Long id : ids) {
            DishVO dish = dishMapper.getById(id);
            Integer status = dish.getStatus();
            //判断当前菜品是否在售卖中
            if (status == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
            SetmealDish setmealDish = setmealDishMapper.getByDishId(id);
            //判断当前菜品是否被关联
            if (setmealDish != null && setmealDish.getSetmealId() != null){
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
            //删除菜品
             dishMapper.deleteById(id);
            //删除口味
            dishFlavorMapper.deleteByDishId(id);
        }
    }

    /**
     * 新增菜品
     *
     * @param dishDTO
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish, "flavors");
        dish.setStatus(StatusConstant.ENABLE);
        dishMapper.save(dish);
        //获取insert语句生成的主键值
        Long id = dish.getId();
//        List<DishFlavor> flavors = dishDTO.getFlavors().stream().map(item -> {
//            DishFlavor dishFlavor = DishFlavor.builder()
//                    .dishId(id)
//                    .name(item.getName())
//                    .value(item.getValue())
//                    .build();
//            return dishFlavor;
//        }).collect(Collectors.toList());
        List<DishFlavor> flavors = dishDTO.getFlavors();

        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(id);
            });
            dishFlavorMapper.saveBetch(flavors);
        }
    }

    /**
     *  修改菜品
     * @param dishDTO
     */
    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        //修改菜品表
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);

        dishMapper.update(dish);
        //删除口味表
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        //新增口味表
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            dishFlavorMapper.saveBetch(flavors);
        }
    }

    /**
     * 用户端根据分类Id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> listByCategoryId(Long categoryId) {

        List<DishVO> dishes = dishMapper.selectByCategoryId(categoryId);
        for (DishVO dish : dishes){
            List<DishFlavor> dishFlavors = dishFlavorMapper.selcetByDishId(dish.getId());
            dish.setFlavors(dishFlavors);
        }

        return dishes;
    }

}
